package com.matriq.cloudmanager.service;

import java.io.FileNotFoundException;

import net.lgpage.util.CrashHandler;
import net.lgpage.util.PromptTool.TagTool;

import org.apache.http.conn.util.InetAddressUtils;

import android.content.Context;

import com.sangfor.ssl.IVpnDelegate;
import com.sangfor.ssl.SFException;
import com.sangfor.ssl.SangforAuth;
import com.sangfor.ssl.common.VpnCommon;

public class VPNService {
	
	private static final String TAG = VPNService.class.getSimpleName();
	private static final String VPN_IP = "125.214.113.102";
    private static final int VPN_PORT = 443;
    private static final String USER = "cs";
    private static final String PASSWD = "111111";
    private SangforAuth sfAuth =null;
	/**
     * 开始初始化VPN，该初始化为异步接口，后续动作通过回调函数通知结果
     *
     * @return 成功返回true，失败返回false，一般情况下返回true
     */
    public boolean initSslVpn()  {
    	sfAuth = SangforAuth.getInstance();
    	TagTool.e(TAG, "VPN连接中...");
        if(!InetAddressUtils.isIPv4Address(VPN_IP)){
        	TagTool.e(TAG, "vpn ipaddress invalid");
            return false;
        }
        long host = VpnCommon.ipToLong(VPN_IP);
        int port = VPN_PORT;
        sfAuth.setLoginParam("10"/*AUTH_CONNECT_TIME_OUT*/, String.valueOf(5));
        if (sfAuth.vpnInit(host, port) == false) {
        	TagTool.e(TAG, "vpn init fail, errno is");
            return false;
        }
        return true;
    }
    public void init(Context context,IVpnDelegate callback) throws SFException{
		sfAuth.init(context, callback, SangforAuth.AUTH_MODULE_EASYAPP);
    }
    /**
     * 处理认证，通过传入认证类型（需要的话可以改变该接口传入一个hashmap的参数用户传入认证参数）.
     * 也可以一次性把认证参数设入，这样就如果认证参数全满足的话就可以一次性认证通过，可见下面屏蔽代码
     *
     * @param authType
     *            认证类型
     * @throws SFException
     */
    public void doVpnLogin(int authType) {
    	TagTool.e(TAG, "doVpnLogin authType ");

        boolean ret = false;
        SangforAuth sfAuth = SangforAuth.getInstance();

        switch (authType) {
            case IVpnDelegate.AUTH_TYPE_CERTIFICATE:

                break;
            case IVpnDelegate.AUTH_TYPE_PASSWORD:
                sfAuth.setLoginParam(IVpnDelegate.PASSWORD_AUTH_USERNAME,USER);
                sfAuth.setLoginParam(IVpnDelegate.PASSWORD_AUTH_PASSWORD, PASSWD);
                sfAuth.setLoginParam(IVpnDelegate.SET_RND_CODE_STR, "");
                ret = sfAuth.vpnLogin(IVpnDelegate.AUTH_TYPE_PASSWORD);
                break;
            case IVpnDelegate.AUTH_TYPE_SMS:
                sfAuth.setLoginParam(IVpnDelegate.SMS_AUTH_CODE, "");
                ret = sfAuth.vpnLogin(IVpnDelegate.AUTH_TYPE_SMS);
                break;
            case IVpnDelegate.AUTH_TYPE_SMS1:
                ret = sfAuth.vpnLogin(IVpnDelegate.AUTH_TYPE_SMS1);
                break;
            default:
                TagTool.e(TAG, "default authType " + authType);
                break;
        }

        if (ret == true) {
           TagTool.e(TAG, "success to call login method");
        } else {
           TagTool.e(TAG, "fail to call login method");
        }

    }

    /*@Override
    public void vpnCallback(int vpnResult, int authType) {
        SangforAuth sfAuth = SangforAuth.getInstance();

        switch (vpnResult) {
            case IVpnDelegate.RESULT_VPN_INIT_FAIL:

                *//**
                 * 初始化vpn失败
                 *//*
               TagTool.e(TAG, "RESULT_VPN_INIT_FAIL, error is " + sfAuth.vpnGeterr());
                displayToast("VPN初始化失败," + sfAuth.vpnGeterr());
                if(progress!=null){
                    progress.hide();
                    progress=null;
                }
                break;

            case IVpnDelegate.RESULT_VPN_INIT_SUCCESS:
                *//**
                 * 初始化vpn成功，接下来就需要开始认证工作了
                 *//*

               TagTool.e(TAG,
                        "RESULT_VPN_INIT_SUCCESS, current vpn status is " + sfAuth.vpnQueryStatus());
                //displayToast("RESULT_VPN_INIT_SUCCESS, current vpn status is "
                //        + sfAuth.vpnQueryStatus());
               TagTool.e(TAG, "vpnResult===================" + vpnResult  + "\nauthType ==================" + authType);
                // 初始化成功，进行认证操作
                doVpnLogin(IVpnDelegate.AUTH_TYPE_PASSWORD);
//				doVpnLogin(IVpnDelegate.AUTH_TYPE_CERTIFICATE)
//				doVpnLogin(authType);
//				String hardidString = sfAuth.vpnQueryHardID();
//				TagTool.e(TAG, "vpn hardid ============================ " + hardidString);
                break;

            case IVpnDelegate.RESULT_VPN_AUTH_FAIL:
                *//**
                 * 认证失败，有可能是传入参数有误，具体信息可通过sfAuth.vpnGeterr()获取
                 *//*
                String errString = sfAuth.vpnGeterr();
               TagTool.e(TAG, "RESULT_VPN_AUTH_FAIL, error is " + sfAuth.vpnGeterr());
                displayToast("VPN认证失败," + sfAuth.vpnGeterr());
                if(progress!=null){
                    progress.hide();
                    progress=null;
                }
                break;

            case IVpnDelegate.RESULT_VPN_AUTH_SUCCESS:
                *//**
                 * 认证成功，认证成功有两种情况，一种是认证通过，可以使用sslvpn功能了，另一种是前一个认证（如：用户名密码认证）通过，
                 * 但需要继续认证（如：需要继续证书认证）
                 *//*

                if (authType == IVpnDelegate.AUTH_TYPE_NONE) {
                   TagTool.e(TAG, "welcom to sangfor sslvpn!");
                    ToastUtils.getInstance().showToast(LoginActivity.this,"VPN连接成功",1);
                    if(progress!=null){
                        progress.hide();
                        progress=null;
                    }
                    // 若为L3vpn流程，认证成功后开启自动开启l3vpn服务
                    if (SangforAuth.getInstance().getModuleUsed() == SangforAuth.AUTH_MODULE_EASYAPP) {
                        // EasyApp流程，认证流程结束，可访问资源。
                        //doResourceRequest();
                    }

                } else {
                   TagTool.e(TAG, "auth success, and need next auth, next auth type is " + authType);
                    //displayToast("auth success, and need next auth, next auth type is " + authType);

                    if (authType == IVpnDelegate.AUTH_TYPE_SMS) {
                        // 输入短信验证码
                        displayToast("you need send sms code.");
                    } else {
                        doVpnLogin(authType);
                    }
                }
                break;
            case IVpnDelegate.RESULT_VPN_AUTH_CANCEL:
               TagTool.e(TAG, "RESULT_VPN_AUTH_CANCEL");
                displayToast("RESULT_VPN_AUTH_CANCEL");
                break;
            case IVpnDelegate.RESULT_VPN_AUTH_LOGOUT:
                *//**
                 * 主动注销（自己主动调用logout接口）或者被动注销（通过控制台把用户踢掉）均会调用该接口
                 *//*

                //tunObserver.stopWatching();
               TagTool.e(TAG, "RESULT_VPN_AUTH_LOGOUT");
                displayToast("RESULT_VPN_AUTH_LOGOUT");
                break;
            case IVpnDelegate.RESULT_VPN_L3VPN_FAIL:
                *//**
                 * L3vpn启动失败，有可能是没有l3vpn资源，具体信息可通过sfAuth.vpnGeterr()获取
                 *//*
               TagTool.e(TAG, "RESULT_VPN_L3VPN_FAIL, error is " + sfAuth.vpnGeterr());
                displayToast("RESULT_VPN_L3VPN_FAIL, error is " + sfAuth.vpnGeterr());
                break;
            case IVpnDelegate.RESULT_VPN_L3VPN_SUCCESS:
                *//**
                 * L3vpn启动成功

                 //				registerNetWorkBroadcasts(); //注册网络监听广播
                 if (tunObserver == null) {
                 tunObserver = new TunObserver();
                 }
                TagTool.e(TAG, "start tun0 observe");
                 tunObserver.startWatching();
                TagTool.e(TAG, "RESULT_VPN_L3VPN_SUCCESS ===== " + SystemConfiguration.getInstance().getSessionId());
                 displayToast("RESULT_VPN_L3VPN_SUCCESS");
                 // L3vpn流程，认证流程结束，可访问资源。
                 doResourceRequest();*//*

                break;
            case IVpnDelegate.VPN_STATUS_ONLINE:
                *//**
                 * 与设备连接建立
                 *//*
               TagTool.e(TAG, "vpn online");
                //displayToast("online");
                break;
            case IVpnDelegate.VPN_STATUS_OFFLINE:
                *//**
                 * 与设备连接断开
                 *//*
               TagTool.e(TAG, "offline");
                displayToast("offline");
                break;
            default:
                *//**
                 * 其它情况，不会发生，如果到该分支说明代码逻辑有误
                 *//*
               TagTool.e(TAG, "default result, vpn result is " + vpnResult);
                //displayToast("default result, vpn result is " + vpnResult);
                break;
        }
    }

    @Override
    public void reloginCallback(int status, int result) {
        switch (status){

            case IVpnDelegate.VPN_START_RELOGIN:
                Log.e(TAG, "relogin callback start relogin start ...");
                break;
            case IVpnDelegate.VPN_END_RELOGIN:
                Log.e(TAG, "relogin callback end relogin ...");
                if (result == IVpnDelegate.VPN_RELOGIN_SUCCESS){
                    Log.e(TAG, "relogin callback, relogin success!");
                } else {
                    Log.e(TAG, "relogin callback, relogin failed");
                }
                break;
        }
    }

    @Override
    public void vpnRndCodeCallback(byte[] data) {
        Log.d(TAG, "vpnRndCodeCallback data: " + Boolean.toString(data==null));
        if (data != null) {
            Drawable drawable = Drawable.createFromStream(new ByteArrayInputStream(data),
                    "rand_code");
            imgbtn_rnd_code.setBackgroundDrawable(drawable);
        }
    }*/
}
